﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using FinPlusCommon;
using Messaging2;
using u = FinPlusUtility.Utility;
using log = Logger.Logger;

namespace FinPlusComponents
{
    public class FinPlusMessaging: FinPlusComponent
    {
        public override string Id { get; set; }
        public override string[] States { get { return new string[] { }; } }
        public override string[] TestStates { get { return new string[] { "IsValid" }; } }
        public override IFinPlusFunctions Model { get { return null; } }
        public override string ModelTest { get { return null; } }
        public override bool IsValid { get; set; }

        public event EventHandler<IFinPlusFunction> OnUpdate;

        private readonly ITransport _tran; 

        //construct
        public FinPlusMessaging(string address, string port, string topic = null)
        {
            if(_tran == null) _tran = new Transport(address, int.Parse(port));
            
            _tran.Listener.MessageRecieved += MessageEvent;
            
            if (!string.IsNullOrEmpty(topic)) Listen(topic);

            IsValid = true;
        }

        //common control interface
        public override void Dock(object component, string dock)
        {
            IsValid = false;
            throw new NotImplementedException();
        }

        public override void Initialise()
        {

        }

        public override void CommandRouter(IFinPlusFunction func)
        {
            try
            {
                CaptureCommand(func);
                Update(func);
            }
            catch (Exception e)
            {
                IsValid = log.Log(Logger.Level.Error, Id, Config, e.Message, e);
            }
        }

        public override void Dispose()
        {
            try
            {
                _tran.Dispose();
            }
            catch (Exception e)
            {
                log.Log(Logger.Level.Warning, e.Message, e);
            }
        }

        //public
        public void Listen(string topic)
        {
            if (_tran != null) _tran.Listen(topic);
        }

        public void Publish(IMessage message)
        {
            if (_tran != null) _tran.Publish(message);
        }

        //private 
        private void Update(IFinPlusFunction func)
        {
            if (OnUpdate != null)
                OnUpdate(this, func);
        }

        //cmds
        private new enum Commands { Update }

        //events 
        private void MessageEvent(object sender, EventArgs a)
        {
            CommandRouter(new Function(((MessageEventArgs)a).Message));
        }
    }
}
